import { Injectable } from '@angular/core';
import { HttpEvent, HttpHandler, HttpInterceptor, HttpRequest } from '@angular/common/http';
import { Observable, tap } from 'rxjs';
import { Store } from '@ngxs/store';
import { Navigate } from '@ngxs/router-plugin';
import { SystemSelector } from '../../store';
import { NzMessageService } from 'ng-zorro-antd/message';

@Injectable()
export class AuthInterceptor implements HttpInterceptor {

  constructor(
      private store: Store,
      private message: NzMessageService,
  ) {
  }

  intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
    const token = this.store.selectSnapshot(SystemSelector.token);
    if (!!token) {
      request = request.clone({
        setHeaders: {
          Authorization: `Basic ${token}`,
        },
      });
    }
    const that = this;
    return next.handle(request).pipe(tap({
      error(e) {
        if (e.status === 401) {
          that.message.error(`你没有权限，请登录`);
          that.store.dispatch(new Navigate(['/login']));
        } else if (e.status === 403) {
          that.message.error(`你没有足够的权限`);
        }
      },
    }));
  }
}
